<template>
	<div>
		<n-tabs model-value="first" size="small" type="segment" class="flex flex-col" style="height: 250px">
			<n-tab-pane name="first" size="small" display-directive="show:lazy" class="f1 h0 flex-col">
				<template #tab>
					<n-space>
						<span>页面</span>
						<my-icon icon="Eleme" />
					</n-space>
				</template>
				<div class="flex s-center m-b-5 p-l-5">
					<el-input v-model="filterText" placeholder="请输入关键字进行过滤" size="small" />
					<n-tooltip trigger="hover">
						<template #trigger>
							<my-icon class="m-x-5 pointer f-s-20" icon="wenjianjiatianjia" @click="insertFn()" />
						</template>
						<span>新增目录</span>
					</n-tooltip>
					<n-tooltip trigger="hover">
						<template #trigger>
							<my-icon class="pointer f-s-20" icon="wenjianshangchuan" @click="importPageFn('0')" />
						</template>
						<span>导入目录</span>
					</n-tooltip>
				</div>
				<el-tree
					ref="treeRef"
					:default-expanded-keys="[$store.chart.pageId || pageId]"
					:current-node-key="$store.chart.pageId || pageId"
					:filter-node-method="filterNode"
					node-key="id"
					:data="$store.chart.pageList"
					highlight-current
					class="f1 h0 overflow-y-auto"
				>
					<template #default="{ node, data }">
						<div
							class="flex m-between s-center w100"
							@click="pageFn(node, data)"
							@contextmenu="handleContextMenu($event, data)"
						>
							<div class="flex s-center">
								<my-icon
									class="m-r-5"
									:icon="
										data.type == 'M' ? (node.expanded ? 'sucai' : 'wenjianjia') : data.isHomePage ? 'Home' : 'Document'
									"
								/>
								<span>{{ data.title }}</span>
							</div>
						</div>
					</template>
				</el-tree>
			</n-tab-pane>

			<n-tab-pane name="second" size="small" display-directive="show:lazy" class="h100 overflow-y-auto">
				<template #tab>
					<n-space>
						<span>母版</span>
						<my-icon icon="HelpFilled" />
					</n-space>
				</template>
				<div class="flex s-center m-b-5 p-l-5">
					<el-input v-model="filterText" placeholder="请输入关键字进行过滤" size="small" />
					<n-tooltip trigger="hover">
						<template #trigger> <my-icon class="m-x-5 pointer f-s-18" icon="DocumentAdd" /> </template>
						<span>新增母版</span>
					</n-tooltip>
				</div>
			</n-tab-pane>
		</n-tabs>

		<!-- 新增目录 -->
		<el-dialog
			:title="dialog.title"
			v-model="dialog.open"
			width="500px"
			append-to-body
			@closed="resetForm(refDialogForm)"
		>
			<my-form
				ref="refDialogForm"
				:model="dialog.form"
				label-width="90px"
				:formItem="
					dialog.title.includes('页面')
						? [{ prop: 'title', label: '页面名称', required: true }]
						: [{ prop: 'title', label: '目录名称', required: true }]
				"
			/>
			<template #footer>
				<el-button @click.prevent="dialog.open = false">取 消</el-button>
				<el-button type="primary" @click.prevent="dialogSubmitFn()">确 定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { downloadTextFile, JSONStringify } from '@u';
import { allCatalog, addCatalog, editCatalog, removeCatalog, exportPage, importPage } from '@a/website';
import { uploadData } from '@a/module';

// 右键菜单数组
import { menuOptions } from '../../hooks/useContextMenu.hook';

/***********************************站点id：websiteId,页面id：pageId ****************************************/
const { websiteId, pageId } = useRoute().params;

/************************页面数据信息******************/
const refDialogForm = shallowRef(),
	dialog = reactive({
		title: '信息',
		open: false,
		form: {
			websiteId
		},
		itemData: {}
	});

// 初始化表格查询逻辑
function loadData() {
	return allCatalog({ id: websiteId }).then((res) => {
		$store.chart.pageList = res.data;
	});
}
loadData();

/***********************************新增修改删除****************************************/
function insertFn(row) {
	resetForm(refDialogForm.value);
	dialog.open = true;
	nextTick(() => {
		dialog.form.parentId = row?.id || '0';
		dialog.title = '新增目录';
		dialog.form.id = undefined;
		dialog.form.type = 'M';
	});
}

function dialogSubmitFn() {
	if (dialog.title.includes('新增')) {
		const { type, title } = dialog.form;
		addCatalog(dialog.form).then((res) => {
			msgSuccess('新增成功！');
			dialog.open = false;
			loadData().then(() => {
				nextTick(() => {
					if (type === 'Y') pageFn(null, { type: 'Y', title, id: res.data });
				});
			});
		});
	}
	if (dialog.title.includes('重命名')) {
		editCatalog(dialog.form).then(() => {
			msgSuccess('修改成功！');
			dialog.open = false;
			loadData();
		});
	}
}

function removeFn() {
	confirm('此操作将删除该数据, 是否继续?')
		.then(() => {
			removeCatalog({ ids: dialog.itemData.id }).then(() => {
				msgSuccess('删除成功');
				loadData();
			});
		})
		.catch(() => {
			msgInfo('已取消删除！');
		});
}

// 右键菜单处理
const menuOptionsData = {
	M: [
		{
			label: '新增目录',
			icon: 'FolderAdd',
			fnHandle: function () {
				insertFn(dialog.itemData);
			}
		},
		{
			label: '新增页面',
			icon: 'CirclePlus',
			fnHandle: function () {
				resetForm(unref(refDialogForm));
				dialog.title = '新增页面';
				dialog.open = true;
				nextTick(() => {
					dialog.form.parentId = dialog.itemData.id;
					dialog.form.id = undefined;
					dialog.form.type = 'Y';
				});
			}
		},
		{
			label: '重命名',
			icon: 'Edit',
			fnHandle: function () {
				resetForm(unref(refDialogForm));
				dialog.title = '目录重命名';
				dialog.open = true;
				nextTick(() => {
					dialog.form = { ...dialog.itemData };
				});
			}
		},
		{
			label: '删除',
			icon: 'CircleClose',
			fnHandle: removeFn
		},
		{
			label: '导出目录',
			icon: 'Download',
			fnHandle: exportPageFn
		},
		{
			label: '导入页面',
			icon: 'Upload',
			fnHandle: importPageFn
		}
	],
	Y: [
		{
			label: '重命名',
			icon: 'Edit',
			fnHandle: function () {
				resetForm(unref(refDialogForm));
				dialog.title = '页面重命名';
				dialog.open = true;
				nextTick(() => {
					dialog.form = { ...dialog.itemData };
				});
			}
		},
		{
			label: '删除',
			icon: 'CircleClose',
			fnHandle: removeFn
		},
		{
			label: '导出页面',
			icon: 'Download',
			fnHandle: exportPageFn
		},
		{
			label: '设置首页',
			icon: 'Home',
			fnHandle: function () {
				confirm('该页面将被设置为首页, 是否继续?')
					.then(() => {
						editCatalog({ id: dialog.itemData.id, isHomePage: '1' }).then(() => {
							msgSuccess('操作成功');
							loadData();
						});
					})
					.catch(() => {
						msgInfo('已取消操作！');
					});
			}
		}
	]
};

// 导入页面/目录
function importPageFn(catalogId) {
	try {
		const ele = document.createElement('input'); // 创建下载链接
		ele.style.display = 'none'; // 隐藏的可下载链接
		ele.type = 'file';
		ele.accept = '.json';
		document.body.appendChild(ele);
		ele.click();
		ele.onchange = async function (e) {
			const [file] = e.target.files || e.dataTransfer.files || this.file.files;

			// 只允许上传 json 格式
			if (!file.type && /\.(?:json)$/.test(file.name)) {
				msgInfo('上传的格式只能是：json 格式！');
				return false;
			}

			// 创建一个formData对象，后期通过ajax上传到服务器
			let formdata = new FormData();
			formdata.append('file', file);

			// 文件上传
			const { data } = await uploadData(formdata);

			// 移除dom
			document.body.removeChild(ele);

			// 页面/目录导入
			await importPage({ websiteId, jsonFileId: data.id, catalogId: catalogId ?? dialog.itemData.id });

			// 查询站点-页面数据
			loadData();

			msgSuccess('操作成功！');
		};
	} catch (error) {
		console.log(error);
	}
}

// 导出页面/目录
function exportPageFn() {
	confirm('此操作将导出该文件, 是否继续?')
		.then(() => {
			exportPage({ id: dialog.itemData.id }).then((res) => {
				downloadTextFile(JSONStringify(res), dialog.itemData.title, 'json');
			});
		})
		.catch(() => {
			msgInfo('已取消操作！');
		});
}

// 鼠标右键逻辑
function handleContextMenu(e, data) {
	e.stopPropagation();
	e.preventDefault();
	// 隐藏旧列表
	$store.chart.rightMenuShow = false;
	/***********设置右键按钮功能**************/
	menuOptions.value = menuOptionsData[data.type];
	dialog.itemData = clone(data);
	nextTick(() => {
		$store.chart.setMousePosition(e.clientX, e.clientY);
		$store.chart.rightMenuShow = true;
	});
}

/***********************************页面点击逻辑************************************/
function pageFn(node, data) {
	if (data.type === 'Y') {
		$store.chart.editCanvasConfig.pageName = data.title;
		$router.push({
			name: 'ChartHome',
			params: { websiteId, pageId: data.id }
		});
		$store.chart.addPageTabs({ id: data.id, title: data.title });
	}
}
/***********************************页面过滤****************************************/
const treeRef = shallowRef(null),
	filterText = ref('');
watch(filterText, (val) => {
	treeRef.value?.filter(val);
});
function filterNode(val, data) {
	if (!val) return true;
	return data.label.includes(val);
}
</script>

<style lang="scss" scoped></style>
